package cn.elead.chaos.email.template.velocity;

import java.io.StringWriter;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;

import cn.elead.chaos.email.domain.CustomMailMessage;
import cn.elead.chaos.email.template.TemplateProcess;

public class VelocityProcess implements TemplateProcess	{

	@Autowired
	private VelocityEngine velocityEngine;

	public String convertTemplate(CustomMailMessage message) {

		String text = message.getText();
		if (StringUtils.isEmpty(text)) {
			return StringUtils.EMPTY;
		} 
		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext(message.getVariables());
		StringWriter writer = new StringWriter();
		// 转换
		velocityEngine.evaluate(context, writer, StringUtils.EMPTY, message.getText());
		text = writer.toString();
		message.setText(text);
		return text;
	}
}
